import React, { useEffect, useMemo, useRef } from 'react';
import { Chart } from '@antv/g2';
import './IndicatorAnalysis.css';
import { DatePicker, Select } from 'antd';
import moment from 'moment';
import dayjs from 'dayjs';

interface EnergyData {
  month: string;
  type: string;
  value: number;
}

const data: EnergyData[] = [
  { month: '1月', type: '门1', value: 350 },
  { month: '1月', type: '门2', value: 280 },
  { month: '1月', type: '门3', value: 220 },
  { month: '2月', type: '门1', value: 400 },
  { month: '2月', type: '门2', value: 320 },
  { month: '2月', type: '门3', value: 250 },
  { month: '3月', type: '门1', value: 380 },
  { month: '3月', type: '门2', value: 300 },
  { month: '3月', type: '门3', value: 230 },
  { month: '4月', type: '门1', value: 420 },
  { month: '4月', type: '门2', value: 340 },
  { month: '4月', type: '门3', value: 260 },
  { month: '5月', type: '门1', value: 390 },
  { month: '5月', type: '门2', value: 310 },
  { month: '5月', type: '门3', value: 240 },
  { month: '6月', type: '门1', value: 410 },
  { month: '6月', type: '门2', value: 330 },
  { month: '6月', type: '门3', value: 270 },
  { month: '7月', type: '门1', value: 430 },
  { month: '7月', type: '门2', value: 350 },
  { month: '7月', type: '门3', value: 280 },
  { month: '8月', type: '门1', value: 440 },
  { month: '8月', type: '门2', value: 360 },
  { month: '8月', type: '门3', value: 290 },
  { month: '9月', type: '门1', value: 420 },
  { month: '9月', type: '门2', value: 340 },
  { month: '9月', type: '门3', value: 260 },
  { month: '10月', type: '门1', value: 450 },
  { month: '10月', type: '门2', value: 370 },
  { month: '10月', type: '门3', value: 300 },
  { month: '11月', type: '门1', value: 460 },
  { month: '11月', type: '门2', value: 380 },
  { month: '11月', type: '门3', value: 310 },
  { month: '12月', type: '门1', value: 470 },
  { month: '12月', type: '门2', value: 390 },
  { month: '12月', type: '门3', value: 320 },
];

const IndicatorAnalysis: React.FC<{ sceneMetric: any, params: any, onChange: (params: any) => void, onAnalysis: () => void, sceneMetricData: any, alarmData: any }> = ({ sceneMetric, params, onChange, onAnalysis, sceneMetricData, alarmData }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const containerRef2 = useRef<HTMLDivElement>(null);
  const chartRef = useRef<Chart | null>(null);
  const chartRef2 = useRef<Chart | null>(null);
  console.log('alarmData', alarmData)

  const chartData = useMemo(() => {
    const list: any[] = []
    Object.keys(sceneMetricData || {}).forEach((key: any) => {
      const item = sceneMetricData[key]
      console.log('item', item)
      item?.forEach((item: any) => {
        list.push({
          name: key,
          时间: moment(item.time).format('YYYY-MM-DD HH:mm'),
          数值: item.value,
          alarm: alarmData[key]?.includes(item.time)
        });
      });
    });
    return list;
  }, [sceneMetricData]);
  console.log('chartData', chartData)

  const pointStyle = (point: any) => {
    console.log('pointStyle called:', point);
    const { alarm } = point;
    let color;
    if (alarm) {
      color = '#d62728'; // 红色
    } else {
      color = '#FFF'; // 默认灰色
    }
    return color
  };

  useEffect(() => {
    const renderChart = () => {
      if (containerRef.current) {
        if (chartRef.current) {
          chartRef.current.destroy();
        }

        const chart = new Chart({
          container: containerRef.current,
          autoFit: true,
          theme: 'dark',
        });

        chart
          .data(chartData)
          .encode('x', '时间')
          .encode('y', '数值')
          .encode('color', 'name')
          .axis('x', {
            label: null
          })
          .axis('y', {
            label: null
          })
        // .scale('x', {
        //   range: [0, 1],
        // })
        // .scale('y', {
        //   domainMin: 0,
        //   nice: true,
        // });

        // chart.line().label({
        //   text: 'value',
        //   style: {
        //     dx: -10,
        //     dy: -12,
        //   },
        // });

        // chart.point().style(pointStyle)
        chart.point().style('fill', pointStyle)

        chart.render();

        chartRef.current = chart;
      }
    };

    renderChart();

    const resizeObserver = new ResizeObserver(() => {
      renderChart();
    });

    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    return () => {
      resizeObserver.disconnect();
      if (chartRef.current) {
        chartRef.current.destroy();
      }
    };
  }, [chartData]);

  console.log('params', params)

  return <div className="indicator-analysis">
    <div className='header'>
      <div className='title-container'>
        <h2 className='title'>指标分析</h2>
        <div className='subTitle'>Index Analysis</div>
      </div>

      <div className='tool-container'>
        {/* 多选 */}
        <Select onChange={(value) => onChange({ ...params, metricIds: value })} style={{
          maxWidth: '440px',
          minWidth: 200,
          height: 37
        }} value={params.metricIds} maxCount={3} mode='multiple' placeholder="选择指标（多选）" options={sceneMetric?.map((item: any) => ({ label: item.name, value: item.id })) as any}></Select>

        {/* 时间选择 */}
        {/* 只能选当前时间 之前*/}
        <DatePicker.RangePicker
          onChange={(value) => onChange({ ...params, start: value?.[0]?.format('YYYY-MM-DD'), end: value?.[1]?.format('YYYY-MM-DD') })}
          placeholder={['开始日期时间', '结束日期时间']}
          disabledDate={(current) => {
            // 不能选择今天之后的日期
            if (current && current > dayjs()) {
              return true;
            }
            // 不能选择7天前的日期
            if (current && current < dayjs().subtract(7, 'days')) {
              return true;
            }
            return false;
          }}
          // 防止报错
          value={[params.start ? dayjs(params.start) : null, params.end ? dayjs(params.end) : null]}
          style={{
            width: '300px',
            minWidth: 200,
          }}
        ></DatePicker.RangePicker>

        <button className='analysis-button' onClick={onAnalysis}>分析</button>
      </div>
    </div>
    <div className="charts-container">
      <div ref={containerRef} className="chart" />
    </div>
  </div >
};

export default IndicatorAnalysis;


